package qx.hyj.demos.controller;

import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import qx.hyj.demos.V0.JsonResult;
import qx.hyj.demos.entity.Book;
import qx.hyj.demos.entity.BookJl;
import qx.hyj.demos.enums.ErrorCode;
import qx.hyj.demos.excep.LibraryException;
import qx.hyj.demos.service.BookService;
import qx.hyj.demos.service.UserService;

import java.util.List;

@RestController
@RequestMapping("/Demo/book")
@ApiOperation(value = "书籍管理")
public class BookController {
    @Autowired
    private UserService userService;
    @Autowired
    private BookService bookService;

    @PostMapping("/borrowbook")
    @ApiOperation(value = "借书")
    public JsonResult<String> borrowBook(@RequestParam String userName, @RequestParam String bookName) {
        try {
            bookService.borrowBook(userName, bookName);
            return new JsonResult<>("借书成功");
        } catch (LibraryException e) {
            e.printStackTrace();
            return new JsonResult<>("借书失败", e.getErrorCode());
        }

    }

    @PostMapping("/returnbook")
    @ApiOperation(value = "还书")
    public JsonResult<String> returnBook(@RequestParam String userName, @RequestParam String bookName) {
        try {
            int money = bookService.returnBook(userName, bookName);
            if (money == 0) {
                return new JsonResult<>("还书成功");
            } else {
                return new JsonResult<>("还书成功，需支付" + money + "元罚款");
            }
        } catch (LibraryException e) {
            e.printStackTrace();
            return new JsonResult<>("还书失败", e.getErrorCode());
        }
    }

    @PostMapping("/getbook")
    @ApiOperation(value = "查找借书记录")
    public JsonResult<List<BookJl>> getBook(@RequestParam String userName) {
        try {
            List<BookJl> books = bookService.getbook(userName);
            return new JsonResult<>(books);
        } catch (LibraryException e) {
            e.printStackTrace();
            return new JsonResult<>(null, e.getErrorCode());
        }
    }

}
